<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico">
  <link rel="mask-icon" href="/images/favicon.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"blog.upup.fun","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="记一些有意思的js题吧。">
<meta property="og:type" content="article">
<meta property="og:title" content="一些比较有趣的JS题">
<meta property="og:url" content="http://blog.upup.fun/2019/06/25/%E4%B8%80%E4%BA%9B%E6%AF%94%E8%BE%83%E6%9C%89%E8%B6%A3%E7%9A%84JS%E9%A2%98/index.html">
<meta property="og:site_name" content="猫头猫">
<meta property="og:description" content="记一些有意思的js题吧。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2019-06-25T08:13:57.000Z">
<meta property="article:modified_time" content="2020-04-17T08:55:10.508Z">
<meta property="article:author" content="猫头猫">
<meta property="article:tag" content="js">
<meta property="article:tag" content="语法">
<meta property="article:tag" content="题目">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://blog.upup.fun/2019/06/25/%E4%B8%80%E4%BA%9B%E6%AF%94%E8%BE%83%E6%9C%89%E8%B6%A3%E7%9A%84JS%E9%A2%98/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>一些比较有趣的JS题 | 猫头猫</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">猫头猫</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-works">

    <a href="/works/" rel="section"><i class="fa fa-smile fa-fw"></i>小作品</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于我</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://blog.upup.fun/2019/06/25/%E4%B8%80%E4%BA%9B%E6%AF%94%E8%BE%83%E6%9C%89%E8%B6%A3%E7%9A%84JS%E9%A2%98/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="猫头猫">
      <meta itemprop="description" content="如果我是一只小猫咪，每天只要喵喵叫。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="猫头猫">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          一些比较有趣的JS题
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-06-25 16:13:57" itemprop="dateCreated datePublished" datetime="2019-06-25T16:13:57+08:00">2019-06-25</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%89%8D%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">前端</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>1.4k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>1 分钟</span>
            </span>
            <div class="post-description">记一些有意思的js题吧。</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p><strong>在网上或者群里看到的一些关于js语法的题目，有的自己一时半会也没想清楚，在这里记录下来，方便以后查阅。</strong></p>
<hr>
<ol>
<li>代码的输出结果？<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">1.0</span> - <span class="number">0.9</span>;</span><br><span class="line"><span class="keyword">if</span>(a === <span class="number">0.1</span>)&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="literal">true</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">else</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="literal">false</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> b = <span class="number">0.8</span> - <span class="number">0.7</span>;</span><br><span class="line"><span class="keyword">if</span>(a === b)&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="literal">true</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">else</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="literal">false</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
答案：false false<blockquote>
<ul>
<li>js的浮点数运算在计算之后都会有一定的精度损失，因此计算之后的结果，也就是a和b，不会是0.1，而是<strong>近似于0.1</strong>的一个浮点数。  </li>
<li>当然，a与b也不是绝对不会相等。对于下面这段代码：<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">var a = 2.0 - 1.9;</span><br><span class="line">if(a === 0.1)&#123;</span><br><span class="line">	console.log(true);</span><br><span class="line">&#125;</span><br><span class="line">else&#123;</span><br><span class="line">	console.log(false);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var b = 3.0 - 2.9;</span><br><span class="line">if(a === b)&#123;</span><br><span class="line">	console.log(true);</span><br><span class="line">&#125;</span><br><span class="line">else&#123;</span><br><span class="line">	console.log(false)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
输出的结果即为false和true。因为损失的精度值完全相同。  </li>
<li>精度损失的问题通常出现在<strong>浮点数运算</strong>与<strong>大整数运算</strong>中。</li>
<li>++解决精度损失的方案++：对浮点数运算，首先对其放大一定倍数，直至变为整数，再缩小相应倍数，得到精确值。</li>
</ul>
</blockquote>
</li>
</ol>
<hr>
<ol>
<li>代码的输出结果？<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">var x = 30;</span><br><span class="line">function test()&#123;</span><br><span class="line">    console.log(x);</span><br><span class="line">    var x = 10;</span><br><span class="line">    console.log(x);</span><br><span class="line">    x = 20;</span><br><span class="line">    function x()&#123;&#125;</span><br><span class="line">    console.log(x);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
答案：function x(){} 10 20<blockquote>
<ul>
<li>出现这个结果的原因是<strong>变量提升</strong>。function在定义时，提升到代码块最顶部的位置，也就是test函数内的第一行。因此，整个代码理解起来相当于：<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">var x = 30;</span><br><span class="line">function test()&#123;</span><br><span class="line">    function x()&#123;&#125;</span><br><span class="line">    console.log(x);</span><br><span class="line">    var x = 10;</span><br><span class="line">    console.log(x);</span><br><span class="line">    x = 20;</span><br><span class="line">    console.log(x);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
因此有上述结果。</li>
</ul>
</blockquote>
</li>
</ol>
<hr>
<ol>
<li>代码的输出结果？<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">var a = &#123;n : 1&#125;</span><br><span class="line">var b = a;</span><br><span class="line">a.x = a = &#123;n : 2&#125;</span><br><span class="line">console.log(a.x)</span><br><span class="line">console.log(b.x)</span><br></pre></td></tr></table></figure>
答案：undefined {n:2}<blockquote>
<ul>
<li>这是由于运算符优先级而导致的问题。<br>在最开始时，a和b共同指向了一个位置A，这个位置存放着{n:1}。<br>之后当执行代码：<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">a.x = a = &#123;n:2&#125;</span><br></pre></td></tr></table></figure>
时，.运算符比赋值运算符优先级高，因此首先计算a.x，也就是位置A中的x。接下来，按照优先级表，从右向左进行赋值。假设{n:2}存放在位置B，那么第二步就是将a指向位置B。而第三步，由于第一步先计算了位置A中的x，因此第三步是将位置A中的x取出，并指向位置B。因此，计算完成之后，位置A存储的值为：{n:1, x:{n:2}}，而位置B存储的值为：{n:2}。显然，最终的结果是b指向位置A，a指向位置B。故而有上述结果。  </li>
<li>在写代码时，<strong>不要写连续赋值</strong>。</li>
</ul>
</blockquote>
</li>
</ol>

    </div>

    
    
    
        <div class="reward-container">
  <div>嘻嘻</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/wechatpay.png" alt="猫头猫 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/images/alipay.png" alt="猫头猫 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/images/wechat_channel.jpg">
            <span class="icon">
              <i class="fab fa-weixin"></i>
            </span>

            <span class="label">WeChat</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/tags/js/" rel="tag"><i class="fa fa-tag"></i> js</a>
              <a href="/tags/%E8%AF%AD%E6%B3%95/" rel="tag"><i class="fa fa-tag"></i> 语法</a>
              <a href="/tags/%E9%A2%98%E7%9B%AE/" rel="tag"><i class="fa fa-tag"></i> 题目</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2019/06/22/%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E7%9A%84%E5%9B%9E%E8%B0%83%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88/" rel="prev" title="异步编程的回调解决方案">
      <i class="fa fa-chevron-left"></i> 异步编程的回调解决方案
    </a></div>
      <div class="post-nav-item">
    <a href="/2019/07/09/%E5%89%8D%E7%AB%AFnode%E9%AB%98%E5%B9%B6%E5%8F%91%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1%E7%AD%96%E7%95%A5-%E7%BD%91%E6%98%93%E4%BA%91%E8%AF%BE%E5%A0%82%E5%90%AC%E8%AF%BE%E7%AC%94%E8%AE%B0/" rel="next" title="前端node高并发负载均衡策略-网易云课堂听课笔记">
      前端node高并发负载均衡策略-网易云课堂听课笔记 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">
      <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=477844082&auto=1&height=66"></iframe>

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="猫头猫"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">猫头猫</p>
  <div class="site-description" itemprop="description">如果我是一只小猫咪，每天只要喵喵叫。</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">31</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">27</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/maotoumao" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;maotoumao" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:lhx_xjtu@163.com" title="E-Mail → mailto:lhx_xjtu@163.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">猫头猫</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">91k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">1:22</span>
   | <a href="http://beian.miit.gov.cn/" rel="noopener" target="_blank">陕ICP备20005224号-2 </a>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

  

</body>
</html>
